<?php

namespace App\Services\Oauth;

use App\Core\Utils\TencentYun\Image;
use App\Models\Oauth\UserLoginLogModel;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cookie;
use App\Http\Resources\Base\UserResource;

/**
 * 封装user基类
 */
class BaseUser
{
    protected $oauthorUserKey = "tongwei:oauth:userkey"; //保存到session中的userkey
    protected $appUserKey = "tongwei:app:user";
    protected $user; // 用户登陆信息
    protected $userId; // 登陆用户id
    protected $sessionId; // 当前会话sessionid
    protected $expire; // 过期时间
    protected $cookieKey = "tongwei:oauth:uidcookiekey";

    public function getUserId()
    {
        return (int)$this->userId;
    }

    public function getUser()
    {
        return (array)$this->user;
    }

    public function checkUser()
    {
        if ($this->userId && $this->user) {
            return true;
        }
        return false;
    }

    /**
     * user对象的属性
     * @return array
     */
    public function getAttribute()
    {
        return array('id', 'name', 'username', 'mobile', 'nickname', 'isHasPassword', 'avatar', 'sex','bbs_uid');
    }

    /**
     * 获取头像
     */
    public function getAvatar()
    {
        if ($this->checkUser()) {
            if (isset(session()->get($this->getSessionKey())['avatar']) && session()->get($this->getSessionKey())['avatar']) {
                $avatar = session()->get($this->getSessionKey())['avatar'];
                $this->setUserValue('avatar', $avatar);
            }
        }
        $data['avatar'] = $this->read('avatar');
        return UserResource::makeAvatarDecode($data)['avatar_view'];
    }

    public function setAvatar($avatar)
    {
        $this->setUserValue('avatar', $avatar);
        return $this;
    }

    /**
     * 将数组里面的值设置到user对象中
     * @param array $array
     * @return $this
     */
    public function updateUserInfo(Array $array)
    {
        foreach ($array as $key => $value) {
            if (in_array($key, $this->getAttribute())) {
                $this->setUserValue($key, $value);
            } else if ($key === 'password') {
                $this->setUserValue('isHasPassword', $value ? true : false);
            }
        }
        return $this;
    }

    /**
     * 退出
     */
    public function loginOut()
    {
        if ($this->userId) {
           UserLoginLogModel::writeLog(UserLoginLogModel::TYPE_LOGIN_OUT, $this->userId);
        }
        //清空session和cookie
        //session($this->getSessionKey(), null);
        session()->forget($this->getSessionKey());
        $this->user = array();
        $this->userId = '';
      //  Cookie::forget($this->getCookieKey());
    }

    /**
     * 检测是否有cookie
     */
    public function checkCookie()
    {
        if ($cookie = Cookie::get($this->getCookieKey())) {
            return $cookie;
        }
        return false;
    }

    /**
     * 设置cookie
     */
    public function setCookie()
    {
            if(!$this->checkCookie()){
            Cookie::queue($this->getCookieKey(), $this->encodeCookie(), 2592000);
        }
    }

    public function encodeCookie()
    {
        $cacheKey = $this->getUserIdKey();
        //redis缓存userid
        Redis::set($cacheKey, $this->userId);
        return $cacheKey;
    }

    public function dencodeCookie($cacheKey)
    {
        return Redis::get($cacheKey);
    }

    public function read($name)
    {
        if (!isset($this->user[$name]) || !$this->user[$name]) {
            $this->user[$name] = isset(session()->get($this->getSessionKey())[$name]) ? session()->get($this->getSessionKey())[$name] : '';
        }
        return $this->user[$name];
    }

    public function write($name, $value)
    {
        $this->user[$name] = $value;
        return $this;
    }

    public function getUserValue($name)
    {
        if (!isset($this->user[$name]) || !$this->user[$name]) {
            $this->user[$name] = isset(session()->get($this->getSessionKey())[$name]) ? session()->get($this->getSessionKey())[$name] : '';
        }
        return $this->user[$name];
    }

    public function setUserValue($name, $value)
    {
        $this->user[$name] = $value;
        return $this;
    }

    public function __call($method, $params)
    {
        list($data, $isOk) = $this->getOrSetData($method, $params);
        if ($isOk) {
            return $data;
        }
    }

    /**
     * 判断一个未知方法是否是对数据的获取get或者设置set操作，是的话就进行相应处理
     *
     */
    protected function getOrSetData($method, $params)
    {
        $data = null;
        $isOk = false;

        if (preg_match('/^(get|set)([a-zA-z0-9]*)$/', $method, $methodInfo)) {
            $isOk = true;
            $dataName = lcfirst($methodInfo[2]);
            if ($methodInfo[1] == 'get') {
                $data = $this->getUserValue($dataName);
            } else {
                $data = $this->setUserValue($dataName, $params[0]);
            }
        }
        return array($data, $isOk);
    }

    /**
     * 获取md5加密后的oauthUserKey值
     * @return string
     */
    public function getOauthUserKey()
    {
        return md5($this->oauthorUserKey);
    }

    /**
     * 获取md5加密后的oauthUserKey值
     * @return string
     */
    public function getSessionKey()
    {
        return md5($this->oauthorUserKey);
    }

    /**
     *获取md5的cookie值
     */
    public function getCookieKey()
    {
        return md5($this->cookieKey);
    }

    public function getUserIdKey()
    {
        $cacheKey = md5(sprintf('cookie:%s:%s', $this->sessionId, $this->userId));
        return $cacheKey;
    }

    /**
     * 返回当前会话的sessionid
     *
     * @return String
     */
    public function getSessionId()
    {
        $app_name = env('APP_NAME').'_session';
        $sessionId = Cookie::get($app_name);
        if (!$sessionId) {
            session()->regenerate();
            $sessionId = Cookie::get($app_name);
        }
        return $sessionId;
    }

    /**
     * 生成缓存key
     * @param $name
     * @return string
     */
    public function makeCacheKey($name)
    {
        return sprintf('Oauth:%s:%s', $name, $this->getSessionId());
    }
}

?>